// pages/points-mall/points-mall.js
Page({
  data: {
    userPoints: 0, // 用户积分
    activeTab: 0, // 当前选中的标签
    goodsList: [], // 商品列表
    allGoodsList: [], // 所有商品数据
    showExchangeDialog: false, // 是否显示兑换确认弹窗
    selectedGoods: null, // 选中的商品
    categories: ['全部商品', '实物商品', '虚拟商品', '优惠券']
  },

  onLoad: function (options) {
    console.log('积分商城页面加载');
    this.loadUserPoints();
    this.loadGoodsList();
  },

  onShow: function () {
    // 页面显示时刷新用户积分
    this.loadUserPoints();
  },

  // 加载用户积分
  loadUserPoints: function() {
    // 模拟获取用户积分数据
    // 实际项目中应该从服务器获取
    const userPoints = wx.getStorageSync('userPoints') || 1000;
    this.setData({
      userPoints: userPoints
    });
  },

  // 加载商品列表
  loadGoodsList: function() {
    // 模拟商品数据
    const mockGoods = [
      {
        id: 1,
        name: '精美手机壳',
        description: '时尚防摔手机保护壳',
        image: '/static/images/image.png',
        points: 200,
        stock: 50,
        category: '实物商品',
        tag: '热门'
      },
      {
        id: 2,
        name: '会员特权卡',
        description: '30天VIP会员权限',
        image: '/static/images/user.png',
        points: 500,
        stock: 999,
        category: '虚拟商品',
        tag: '推荐'
      },
      {
        id: 3,
        name: '咖啡优惠券',
        description: '星巴克20元代金券',
        image: '/static/images/comment.png',
        points: 150,
        stock: 30,
        category: '优惠券'
      },
      {
        id: 4,
        name: '蓝牙耳机',
        description: '无线蓝牙立体声耳机',
        image: '/static/images/home.png',
        points: 800,
        stock: 20,
        category: '实物商品',
        tag: '新品'
      },
      {
        id: 5,
        name: '视频会员',
        description: '腾讯视频月度会员',
        image: '/static/images/hotel-phone.png',
        points: 300,
        stock: 999,
        category: '虚拟商品'
      }
    ];

    this.setData({
      allGoodsList: mockGoods,
      goodsList: mockGoods
    });
  },

  // 标签切换
  onTabChange: function(event) {
    const activeTab = event.detail.index;
    this.setData({ activeTab });
    this.filterGoodsByCategory(activeTab);
  },

  // 根据分类筛选商品
  filterGoodsByCategory: function(tabIndex) {
    const { allGoodsList, categories } = this.data;
    let filteredGoods = allGoodsList;

    if (tabIndex > 0) {
      const category = categories[tabIndex];
      filteredGoods = allGoodsList.filter(item => item.category === category);
    }

    this.setData({
      goodsList: filteredGoods
    });
  },

  // 商品点击
  onGoodsClick: function(event) {
    const item = event.currentTarget.dataset.item;
    console.log('点击商品:', item);
    // 可以跳转到商品详情页
  },

  // 兑换按钮点击
  onExchangeClick: function(event) {
    event.stopPropagation(); // 阻止事件冒泡
    const item = event.currentTarget.dataset.item;
    
    // 检查积分是否足够
    if (this.data.userPoints < item.points) {
      wx.showToast({
        title: '积分不足',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 检查库存
    if (item.stock <= 0) {
      wx.showToast({
        title: '商品已售罄',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    this.setData({
      selectedGoods: item,
      showExchangeDialog: true
    });
  },

  // 确认兑换
  confirmExchange: function() {
    const { selectedGoods, userPoints } = this.data;
    
    if (!selectedGoods) return;

    // 扣除积分
    const newPoints = userPoints - selectedGoods.points;
    
    // 更新本地积分（实际项目中应该调用API）
    wx.setStorageSync('userPoints', newPoints);
    
    // 更新商品库存
    const updatedGoodsList = this.data.goodsList.map(item => {
      if (item.id === selectedGoods.id) {
        return { ...item, stock: item.stock - 1 };
      }
      return item;
    });

    this.setData({
      userPoints: newPoints,
      goodsList: updatedGoodsList,
      showExchangeDialog: false,
      selectedGoods: null
    });

    wx.showToast({
      title: '兑换成功',
      icon: 'success',
      duration: 2000
    });

    // 记录兑换历史（实际项目中应该保存到服务器）
    this.saveExchangeRecord(selectedGoods);
  },

  // 取消兑换
  cancelExchange: function() {
    this.setData({
      showExchangeDialog: false,
      selectedGoods: null
    });
  },

  // 保存兑换记录
  saveExchangeRecord: function(goods) {
    const records = wx.getStorageSync('exchangeRecords') || [];
    const newRecord = {
      id: Date.now(),
      goodsId: goods.id,
      goodsName: goods.name,
      goodsImage: goods.image,
      points: goods.points,
      exchangeTime: new Date().toISOString(),
      status: 'success'
    };
    
    records.unshift(newRecord);
    wx.setStorageSync('exchangeRecords', records);
  },

  // 跳转到兑换记录页面
  goToExchangeRecord: function() {
    wx.navigateTo({
      url: '/pages/exchange-record/exchange-record',
      fail: function(err) {
        console.error('跳转兑换记录页面失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  }
});
